<?php
/**********************************************************
DoExpressCheckoutPayment.php

This functionality is called to complete the payment with
PayPal and display the result to the buyer.

The code constructs and sends the DoExpressCheckoutPayment
request string to the PayPal server.

Called by GetExpressCheckoutDetails.php.

Calls CallerService.php and APIError.php.

**********************************************************/

require_once "./services/webservices.php";
require_once('Mail.php');
include_once('WidgetShoppingCart.php'); 
session_start();
$page_title = "Payment Page";
include('./includes/header.php');
$cart = unserialize($_SESSION['cart']);

$cartidentifier = $cart->identifier;
$shippingidentifier = $_SESSION['shipping_identifier'];

if($cartidentifier == $shippingidentifier)
{
   
    ini_set('session.bug_compat_42',0);
    ini_set('session.bug_compat_warn',0);

    /* Gather the information to make the final call to
       finalize the PayPal payment.  The variable nvpstr
       holds the name value pairs
       */
    $token =urlencode( $_SESSION['token']);
    $paymentAmount =urlencode ($_SESSION['total_after_shipping']);  
    $paymentType = urlencode($_SESSION['paymentType']);
    $currCodeType = urlencode($_SESSION['currCodeType']);
    $payerID = urlencode($_SESSION['payer_id']);
    $serverName = urlencode($_SERVER['SERVER_NAME']);

    $nvpstr='&TOKEN='.$token.'&PAYERID='.$payerID.'&PAYMENTACTION='.$paymentType.'&AMT='.$paymentAmount.'&CURRENCYCODE='.$currCodeType.'&IPADDRESS='.$serverName ;
    
     /* Make the call to PayPal to finalize payment
        If an error occured, show the resulting errors
        */
    
    $paypalhttppost = new paypalhttppost();
    $resArray = $paypalhttppost->PPWebservice("DoExpressCheckoutPayment",$nvpstr);
    

    /* Display the API response back to the browser.
       If the response from PayPal was a success, display the response parameters'
       If the response was an error, display the errors received using APIError.php.
       */
    $ack = strtoupper($resArray["ACK"]);






    $true = "true";
    if($ack != 'SUCCESS' && $ack != 'SUCCESSWITHWARNING')
    {
        echo '<br />error<br /><br />';
	    $_SESSION['reshash']=$resArray;
	    $location = "APIError.php";
	    header("Location: $location");
    }
    else
    {
       
        
        $order_id = strtoupper($resArray["TRANSACTIONID"]);
        
        $correlation_id = $resArray["CORRELATIONID"];  
       
  
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////     
            $shipping_first_name = $_SESSION['shipping_first_name'];
            $shipping_last_name = $_SESSION['shipping_last_name'];
            $shipping_full_name = $shipping_first_name . " " . $shipping_last_name;
            $shipping_street_address = $_SESSION['shipping_street_address'];
            $shipping_city = $_SESSION['shipping_city'];
            $shipping_state = $_SESSION['shipping_state'];
            $shipping_zip_code = $_SESSION['shipping_zip_code'];
            $shipping_carrier_name = $_SESSION['carrier_name'];
            $service_name = $_SESSION['service_name'];
            $service_id = $_SESSION['service_id'];
            $items_total = $_SESSION['items_total'];
            $shipping_total = number_format($_SESSION['shipping_total'], 2, '.', '');
            $total = number_format($_SESSION['total_after_shipping'], 2, '.', '');; 
            $shiptocountrycode =    "US";

        
            
            $payment_first_name = $_SESSION['payment_first_name'];
            $payment_last_name = $_SESSION['payment_last_name'];
            $payment_email = $_SESSION['payment_email'];
            $payment_payerid = $_SESSION['payment_payerid'];
            $_SESSION['order_id'] = $order_id;
           
            $API_IPaddress = $_SERVER['REMOTE_ADDR'];  
            
            
         
            $companynamearray = file('./configurational/companyname.php');        
            $companynamestring = "";
            foreach($companynamearray as $key => $value)
            {
                if(strpos($value, "companyname") !== false)
                {
                    $companynamestring = $value;
                }
            }
            $companynamearray = explode("=", $companynamestring);
            $companyname = trim($companynamearray[1]);    
            
            $mailarray = file('./configurational/mailconfiguration.php');
            $mailserverstring = "";
            $portstring = "";
            $usernamestring = "";
            $passwordstring = "";
            foreach($mailarray as $key => $value)
            {
                if(strpos($value, "mailserver") !== false)
                {
                    $mailserverstring = $value;
                }
                if(strpos($value, "port") !== false)
                {
                   $portstring = $value; 
                }
                if(strpos($value, "username") !== false)
                {
                    $usernamestring = $value;
                }
                if(strpos($value, "password") !== false)
                {
                    $passwordstring = $value;
                }
            }
            $mailusernamearray = explode("=", $usernamestring);
            $username = trim($mailusernamearray[1]);
            $passwordarray = explode("=", $passwordstring);
            $password = trim($passwordarray[1]);
            $portarray = explode("=", $portstring);
            $port = trim($portarray[1]);
            $hostarray = explode("=", $mailserverstring);
            $host = trim($hostarray[1]); 
         
            
            $email_string = "Thank you for your purchase from " . $companyname .  ".\nIn this email You will find the items that you purchased, and your shipping and billing information. You will also recieve the order number. \nIf you have questions about your order, email " . $username . ".  Include the order number in the subject. \nYou should recieve an email with your package(s) tracking information when your item has shipped. \n\n\n";
                 
             //insert statement to shipping table. 
             $shipping_object = new shipping();
           
     
             $shipping_object->first_name = $shipping_first_name;
             $shipping_object->last_name = $shipping_last_name;
             $shipping_object->street_address = $shipping_street_address;
             $shipping_object->city = $shipping_city;
             $shipping_object->state = $shipping_state;
             $shipping_object->zip_code = $shipping_zip_code;
             $shipping_object->service = $service_name;
             $shipping_object->carrier_name = $shipping_carrier_name; 
             $shipping_object->shipping_total = $shipping_total;
             $shipping_order_object->ip_address = $API_IPaddress;           
             $result = $shipping_object->addshippinginformation();
         
             $xml = new SimpleXMLElement($result);
            
             if($xml->added=="")
             {   
                 $shippingstatus = "false";
             }
             else
             {
               
                $shippingstatus = "true";
             }
         
            //insert statement to payment table. each Insert statement inserts: order id # first_name, correlation_id, middle_initial, last_name, street_address, city, state, zip_code, 
            $order_status = "incomplete";  
                      
            $payment_order_object = new payment();
            $payment_order_object->amount = $total;
            $payment_order_object->order_status = 'incomplete';
            $payment_order_object->payment_type = 'paypal';
            $payment_order_object->ip_address = $API_IPaddress;
            $payment_order_object->order_id = $order_id; 
            $payment_order_object->correlation_id = $correlation_id; 
            $payment_order_object->payer_id = $payment_payerid;
            $payment_order_object->first_name = $payment_first_name;
            $payment_order_object->last_name = $payment_last_name;
            $payment_order_object->email = $payment_email;
            
              
            
            $result = $payment_order_object->addgeneralpaymentinformation();
            $xml = new SimpleXMLElement($result);
            if($xml->item_id != 0)
            {
                $paymentstatus ="true";
            }
            else
            {
                $paymentstatus ="false"; 
            }
            $creditcardPaymentResponse = $payment_order_object->addpaypalpaymentinformation();
            $creditcardPaymentXml = new SimpleXMLElement($creditcardPaymentResponse);
            if($xml->item_id != 0)
            {
                $paymentstatus ="true";
            }
            else
            {
                $paymentstatus ="false"; 
            }
            
            $note = "Order Submitted";
            $getrequest_history = new orders_history();  
            $getrequest_history->order_id = $order_id;
            $getrequest_history->order_status = $order_status;
            $getrequest_history->note = $note;
            $getresponse_history = $getrequest_history->addordershistoryevent();
            $xml = new SimpleXMLElement($getresponse_history);
            if(isset($xml->item_id) && $xml->item_id != "")
            {
                $orderhistorystatus = "true";
            }
            else
            {
                $orderhistorystatus = "false";
            }
            //write and populate strings with order information to be sent through email   
            $shipping_string = "\nShipping information: \n\n First Name:" . $shipping_first_name . "\n Last Name:" . $shipping_last_name . "\n Street Address:" . $shipping_street_address . "\n City:" . $shipping_city . "\n State:" . $shipping_state . "\n Zip Code:" . $shipping_zip_code . "\n Shipping Method:" . $shipping_carrier_name . ":" . $service_name . "\n Shipping Cost:" . $shipping_total . "\n\n\n";   
            $email_string = $email_string . "\nOrder ID:" . $order_id . "\n\n" . $shipping_string;
            $payment_string = "Payment information: \n\n  First Name:" . $payment_first_name . "\n Last Name" . $payment_last_name;             
            $email_string = $email_string . $payment_string;
            $cart_string = "";          
            $admin_cart_string = "";          
            //this foreach statement parses a string that contains all of the items in the order in xml format
            //also populates and writes the cart contents onto a string to be sent as a confirmation email
            $order_object = new orders();
            $itemization = "<xml>";   
            $tmpcartnum = 0; 
           
           
            $cart = unserialize($_SESSION['cart']); 
              
            foreach ($cart->items as $id => $info) 
            {
                
                //must account for specialized items vs non specialized items 
                $current_id = "";
                $specific_name = "";
                        $gw_id = $info['gw_id'];
                        $sw_id = $info['sw_id'];
                        if($sw_id == "")
                        {
                            $name2 = $info['name']; 
                            $current_id = $gw_id;
                        }
                        else
                        {   
                            $current_id = $sw_id;
                            $name2 = $info['name'];
                            $name2 = urldecode($name2); 
                            
                                     
                            
                            $cart_name = new SimpleXMLElement($name2);
                            $gen_name = $cart_name->gw_name;
                         
                            
                            $xml_build = "";
                            
                            $specific_name = $gen_name . ' [';
                            $xml_build .= "<gw_name>" . $gen_name . "</gw_name>";
                            foreach($cart_name->Item as $eachitem2)
                            {
                                $isd_id_cart = $eachitem2->isd_id;
                                $isc_id_cart = $eachitem2->isc_id;
                                $category = $eachitem2->category;
                                $descriptor = $eachitem2->descriptor;
                                $specific_name .= $category . ":" . $descriptor . " ";
                                $xml_build .= "<descriptor_item><isd_id>" . $isd_id_cart . "</isd_id>" . "<descriptor>" . $descriptor . "</descriptor>" . "<isc_id>" . $isc_id_cart . "</isc_id>" . "<category>" . $category . "</category></descriptor_item>";
                                $name2 = (string)$xml_build;
                             
                                   
                            }
                            $specific_name .= "]";
                            
                        
                        }
                       
                        $qty = $info['qty'];
                        $price = $info['price'];
                        $cart_string = $cart_string . "\n\nItem:" . $specific_name . "\nQuantity:" . $qty . "\nPrice per Unit:" . $price;
                        $admin_cart_string .= $admin_cart_string . "\n\n Item ID:" . $current_id . "\nItem:" . $specific_name . "\nQuantity:" . $qty . "\nPrice per Unit:" . $price;     
                        $itemization = $itemization . '<Item><order_id>' . $order_id . '</order_id><gw_id>' . $gw_id . '</gw_id><sw_id>' . $sw_id . '</sw_id><name>' . $name2. '</name><qty>' . $qty . '</qty><price>' . $price . '</price></Item>'; 
                        $tmpcartnum++;
                       
         
              }
              $cart_string = "\n\nItems Purchased:" . $cart_string;
              $admin_cart_string = "\n\nItems Purchased:" . $admin_cart_string;
              $itemization .="</xml>";   
              
            //this sends the xml string that we just created to webservices to be inserted in the database
            $order_object->itemization = $itemization;
            $order_object->order_id = $order_id;
            $order_object->ip_address = $API_IPaddress;           
            $result = $order_object->addorderinformation();
                                                                                                                                                         
            $xml = new SimpleXMLElement($result);
            $number_inserted = $xml->number_inserted;
            //if number inserted is not equal to the  number in cart than set orderstatus to false which will trigger an email to the admin with the order information for farthur inspection 
            if($number_inserted == $tmpcartnum)
            {
                $orderstatus ="true";
            }
            else
            {
                $orderstatus ="false"; 
            }
             $thankyou = "Order Complete. You will recieve an email soon with your order information. Thank you for shopping with " . $companyname . ".";                     

            //complete string to be sent as email for purchase confirmation purposes.
            $email_string = $email_string . $cart_string;                                
            $purchase_total = "\n\nTotal After Shipping:" .  $total;
            $email_string = $email_string . $purchase_total;
            
            
            
            $boxesorganized = $_SESSION['boxesorganized'];                                    
            foreach($boxesorganized as $boxnumber => $boxarray)
            {
                $order_object->status = "not shipped";
                $boxitemReturn = $order_object->addorderbox();
                $boxitemXml = new SimpleXMLElement($boxitemReturn);
                $order_box_id = $boxitemXml->order_box_id;
                
                foreach($boxarray as $key => $current_item_id_weight_array)
                {
                    foreach($current_item_id_weight_array as $current_item_id => $current_item_weight)
                    {         
                        $order_object->order_box_id = $order_box_id;
                        $order_object->item_id = $current_item_id;
                        $order_object->addorderboxitem();
                    }
                }          
            }
            
            
            //send notification email to admin if any of the order details are not recorded in the database. the admin will get an email with the full order info
            $adminmsg = "ORDER ID:" . $order_id . "\n" . $payment_string . $shipping_string . $admin_cart_string . "\n" . "Grand Total:" . $purchase_total . "\n";     
            if($shippingstatus=="false" || $orderstatus=="false" || $paymentstatus=="false" || $orderhistorystatus=="false")
            {     
                $from = $username;
                $to = $username;
                $body = $adminmsg; 
                $subject = "ORDER FINALIZATION ERROR. PLEASE READ EMAIL, CHECK ORDER FROM ADMIN SIDE, AND CONFIRM/FIX MISSING ITEMS."; 
                $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject);
                $smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));

                $mail = $smtp->send($to, $headers, $body);
                
              
            }
            
            
            
            //this email is sent to the purchaser    
            $from = $username;
            $to = $payment_email;
            $body = $email_string; 
            $subject = $companyname . ": Your Recent Purchase Information";
            $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject);
            $smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));
            $mail = $smtp->send($to, $headers, $body);
           
           
            //email the person in charge of controlling incoming order information. 
            $from = $username;
            $to = $username;
            $body = $adminmsg; 
            $subject = "Incoming Order Needs Processing"; 
            $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject);
            $smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));

            $mail = $smtp->send($to, $headers, $body);
        
            session_unset(); 
        
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////     
       
        
    }

    ?>


    <html>
    <head>
        <title>PayPal PHP SDK - DoExpressCheckoutPayment API</title>
        <link href="sdk.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <br />
    <br />
            <?php echo $thankyou; ?>
		    


        <table width =400>
                                            
            
        </table>
        </center>

    </body>
    </html>
    
<?php
}
else
{
?>
     <html>
    <head>
        <title>Paypal Payment Error</title>
      
    </head>
    <body>
            <br>
            <center>
            <form action="./cart.php" method="POST">
            <input type="submit" value="Go To Cart" />
            </form>
           
            <br><br>
            <b>Your payment was not submitted because your cart values were changed during the checkout procedure</b><br />
            <b>You have not been charged for the transaction. Please go back to the cart page and begin the checkout procedure again</b>
            


      
        </center>
      
    </body>
    </html>
<?php
}
?>